﻿define(['jquery', 'backbone', 'underscore', 'mediator', 'proxy'], function ($, Backbone, _, mediator, proxy) {
    var orderFromView = Backbone.View.extend({
        el: '#modal',

        events: {
            "click #saveModal": "save",
            "click #closeModal": "close"
        },

        initialize: function (params) {
            this.template = _.template($("#order-form-template").html());

            _.bindAll(this);
        },

        render: function (params) {
            var that = this;

            if (params && params.orderId) {
                proxy.getOrderById({
                    data: {
                        orderId: params.orderId
                    },
                    success: function (data) {
                        $(that.el).html(that.template({
                            action: 'Update',
                            orderId: params.orderId,
                            orderStatus: data.Status,
                            orderCurrency: data.Currency,
                            customerName: data.Customer.Name,
                            customerEmail: data.Customer.Email
                        }));

                        $(that.el).find('#orderForm').modal();
                    }
                });
            } else {
                $(this.el).html(this.template({
                    action: 'New',
                    orderId: '',
                    orderStatus: '',
                    orderCurrency: 'ARS',
                    customerName: '',
                    customerEmail: ''
                }));

                $(this.el).find('#orderForm').modal();
            }

            return this;
        },

        save: function (e) {
            var order = {
                orderId: $("#form").attr("data-id"),
                orderCurrency: $("#orderCurrency").val(),
                orderStatus: $("#orderStatus").val(),
                customerName: $("#customerName").val(),
                customerEmail: $("#customerEmail").val()
            }, action = $("#form").attr("data-action"),
               that = this;

            if (action === "New") {
                delete order.orderId;

                proxy.createOrder({
                    data: order,
                    success: function () {
                        mediator.publish("orders::refresh");
                        that.close();
                    }
                });
            } else {
                proxy.updateOrder({
                    data: order,
                    success: function () {
                        mediator.publish("orders::refresh");
                        that.close();
                    }
                });
            }

            e.preventDefault();
        },

        close: function () {
            $('#orderForm').modal('hide');
        }
    });

    return new orderFromView();
});